$(document).ready(

);

function create() {
    var table = document.getElementById("t");
    var rowLength = table.rows.length;
    var colLength = table.rows[0].cells.length;
    for (var j = 2; j < rowLength - 1; j++) {
        for (var k = 0; k < colLength; k++) {
            var i = k
            if (k > 4)
                i--;
            if (k > 6)
                i--;
            table.rows[j].cells[k].getElementsByTagName("input")[0].id = (j - 2) + '_' + i;
        }
    }
}


function trimTail(str) {
    var tail = str.substring(0, str.length - 1);
    return tail;
}
/**
 * main function that is to be called to read table content before saving
 */
function readTable(t, action) {
    var table = document.getElementById(t);
    var rowLength = table.rows.length;
    var colLength = table.rows[0].cells.length - 1;
    var body = "";

    var changed = 0;
    var xbody = "";
    for (var j = 2; j < rowLength - 1; j++) {
        body = "\"\",";
        var changedElement = 0;
        for (var k = 0; k < colLength; k++) {// reading content of each column
            if (k != 5 && k != 7 && k != 10) {
                var x = table.rows[j].cells[k].getElementsByTagName("input");
                if (hasClass(x[0], 'changed')) {
                    changedElement = 1;
                    changed = 1;
                }
                var res = x[0].value;
                body += "\"" + res + "\",";
            }
        }

        if (changedElement == 1 && j != rowLength - 2) {
            xbody += trimTail(body) + '\r\n';
        }
    }
    if (action == "save_file") {
        sendcsv(xbody);
    } else {
        if (changed == 1) {
            post_to_url("/result/" + document.getElementsByClassName("shopmaker")[0].value + "/", {"content":xbody, "filename":_getDate() + _getTime() + ".csv"}, "post");
        } else {
            alert("Данные не изменились");
        }
    }
}
function saveTable(t, action) {
    var table = document.getElementById(t);
    var rowLength = table.rows.length;
    var colLength = table.rows[0].cells.length;
    var body = "";

    var changed = 0;
    var xbody = "";
    for (var j = 1; j < rowLength - 1; j++) {
        body = "\"\",";
        for (var k = 0; k < colLength; k++) {// reading content of each column
            if (k != 5 && k != 7) {
                if (k == 6 && table.rows[j].cells[4].innerText < table.rows[j].cells[5].innerText) {
                    body += "\"\",";
                } else {
                    var x = table.rows[j].cells[k].innerText;
                    var res = x;
                    body += "\"" + res + "\",";
                }
            }
        }
        xbody += trimTail(body) + '\r\n';
    }
    if (action == "save_file") {
        sendcsv(xbody);
    }
}

function sendcsv(body) {
    $.ajax({
        type:'POST',
        url:"/savefile/" + document.getElementsByClassName("shopmaker")[0].value + "/",
        data:{"content":body, "filename":_getDate() + _getTime() + ".csv"},
        success:function (url) {
            window.open(url);
//            var iframe = document.createElement("iframe");
//            iframe.setAttribute("src", url);
//            iframe.setAttribute("style", "display: none");
//            document.body.appendChild(iframe);
        }
    });
}
function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    form.setAttribute("target", "_blank")

    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

function _getDate() {
    var month_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    var d = new Date();
    var current_date = d.getDate();
    var current_month = d.getMonth();
    var current_year = d.getFullYear();

    return current_date + "_" + month_names[current_month] + "_" + current_year;

}
function _getTime() {
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();

    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    return "_" + hours + "_" + minutes;
}

function changeAttributeSet(t) {
    t.nextSibling.nextSibling.value = t.value
    changeVerify(t.nextElementSibling.id, t.value);
}

function getShopmaker() {
    return document.getElementsByClassName("shopmaker")[0].value;
}

function changeVerify(id, value) {
    if (!value) {
        value = "null"
    }
    var res;
    $.ajax({
        type:'POST',
        url:"/changeverify/" + getShopmaker() + "/",
        data:{"id":id, "value":value},
        success:function (result) {
            if (result) {
                if (result == "True") {
                    if ($('#' + id).hasClass("changed"))
                        $('#' + id).removeClass("changed");
                    if (document.getElementById(id).previousElementSibling)
                        document.getElementById(id).previousElementSibling.className = "";
                }
                else {
                    if (!$('#' + id).hasClass("changed"))
                        $('#' + id).addClass("changed");
                    if (document.getElementById(id).previousElementSibling)
                        document.getElementById(id).previousElementSibling.className = "changed";
                }
            }
        }
    });
}

function hasClass(element, classNameToTestFor) {
    var classNames = element.className.split(' ');
    for (var i = 0; i < classNames.length; i++) {
        if (classNames[i].toLowerCase() == classNameToTestFor.toLowerCase()) {
            return true;
        }
    }
    return false;
}

$(document).ready(function () {

    $("#calendar1, #calendar2").calendar();

    $("#calendar1_alert").click(function () {
        alert(popUpCal.parseDate($('#calendar1').val()))
    });

});

function csvToTable(id, csvFile, method) {

    var table = document.createElement("table");
    table.id = "t";
    var thead = document.createElement("thead");
    thead.innerHTML = "<th><input disabled='true' style=\"border: none\" value=\"тип\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"набор атрибутов\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"sku\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"названия товара\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"цена, грн\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"цена, usd\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"специальная цена, грн\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"специальная цена, usd\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"специальная цена с\"></th>" +
        "<th><input disabled='true' style=\"border: none\" value=\"специальная цена по\"></th>";


    table.appendChild(thead);

    document.getElementById(id).appendChild(table);
    var csvContent = ""
    $.get(csvFile, function (data) {
        table.appendChild(getTbodyByContent(data));
    });

}
function getTbodyByContent(content) {
    var tbody = document.createElement("tbody");
    var arrayTr = content.split("\r\n");
    for (var i = 1; i < arrayTr.length; i++) {
        var tr = document.createElement("tr");
        var arrayTd = arrayTr[i].split("\",\"")
        arrayTd[0] = arrayTd[0].replace("\"", "");
        arrayTd[arrayTd.length - 1] = arrayTd[arrayTd.length - 1].replace("\"", "")
        var rowLen = arrayTd.length
        for (var j = 1; j < rowLen; j++) {
            var td = document.createElement("td");
            var input = document.createElement("input");
            input.value = arrayTd[j];
            td.appendChild(input);
            tr.appendChild(td);
            if (j == 5 || j == 6) {
                var td2 = document.createElement("td");
                var input = document.createElement("input");
                if (arrayTd[j] != "")
                    input.value = (parseFloat(arrayTd[j]) / parseFloat($('#currency').val())).toFixed(2);
                td2.appendChild(input);
                tr.appendChild(td2);
            }
        }
        tbody.appendChild(tr);
    }
    return tbody;
}

function nextCurrencyRate(el) {
    if (el.value != "") {
        el.parentElement.nextElementSibling.children[0].value = (parseFloat(el.value) / parseFloat(document.getElementById('currency').value)).toFixed(2);
        el.value = parseFloat(el.value);
    } else {
        el.parentElement.nextElementSibling.children[0].value = ""
    }
    el.parentElement.nextElementSibling.children[0].className = el.className;
}

function previousCurrencyRate(el) {
    if (el.value != "") {
        el.parentElement.previousElementSibling.children[0].value = (parseFloat(el.value) * parseFloat(document.getElementById('currency').value)).toFixed(2);
        el.value = parseFloat(el.value);
    } else {
        el.parentElement.previousElementSibling.children[0].value = ""
    }
    el.parentElement.nextElementSibling.children[0].className = el.className;
}